import argparse
from pathlib import Path

from moviepy.editor import AudioFileClip, concatenate_audioclips

parser = argparse.ArgumentParser()

parser.add_argument(
    '-i',
    '--input',
    nargs='+',
    metavar='input',
    required=True,
    help='The input files path of the audio, split by whitespace'
)

parser.add_argument(
    '-o',
    '--output',
    metavar='output',
    required=False,
    help='The output file path of the new audio'
)

args = parser.parse_args()

try:
    clips = []
    first_file = None
    for item in args.input:
        input_file = Path(item)
        if first_file is None:
            first_file = input_file
        if not input_file.is_absolute():
            input_file = Path.cwd() / input_file
        if input_file.exists():
            clip = AudioFileClip(item)  # use string, not Path
            clips.append(clip)
        else:
            print(f'No such file: {input_file}')

    if len(clips) > 0:
        final_clip = concatenate_audioclips(clips)

        if args.output is not None:
            output_file = Path(args.output)
            if not output_file.is_absolute():
                output_file = Path.cwd() / output_file
        else:
            output_file = first_file.parent / f'{first_file.stem}-merge{first_file.suffix}'
        final_clip.write_audiofile(output_file)
    else:
        print('No file to merge')
except Exception as e:
    print(e)
